<template>
  <PageWrapper title="修改当前用户密码" content="修改成功后会自动退出当前登录！">
    <div class="py-8 bg-white flex flex-col justify-center items-center">
      <BasicForm @register="register" />
      <div class="flex justify-center">
        <Authority value="resetBtn">
          <a-button @click="resetFields"> 重置 </a-button>
        </Authority>
        <Authority value="confirmBtn">
          <a-button class="!ml-4" type="primary" @click="handleSubmit" :loading="loading">
            确认
          </a-button>
        </Authority>
      </div>
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { BasicForm, useForm } from '/@/components/Form';

  import { formSchema } from './pwd.data';
  import { modifyUserPwd } from '/@/api/system/system';
  import { UserPwdReq } from '/@/api/system/modal/userPwdModel';
  import { useMessage } from '/@/hooks/web/useMessage';
  import Authority from '/@/components/Authority/src/Authority.vue';

  export default defineComponent({
    name: 'ChangePassword',
    components: { Authority, BasicForm, PageWrapper },
    setup() {
      const loading = ref(false);
      const { createMessage } = useMessage();
      const [register, { validate, resetFields }] = useForm({
        size: 'large',
        baseColProps: { span: 24 },
        labelWidth: 100,
        showActionButtonGroup: false,
        schemas: formSchema,
      });

      async function handleSubmit() {
        loading.value = true;
        try {
          const values = await validate();
          const { passwordOld, passwordNew, confirmPassword } = values;
          const userPwdReq: UserPwdReq = {
            password: passwordOld,
            newPassword: passwordNew,
            confirmPassword: confirmPassword,
          };
          await modifyUserPwd(userPwdReq);
          createMessage.success('当前用户密码修改成功');
          loading.value = false;
        } catch (error: any) {
          loading.value = false;
          const { response, message } = error || {};
          const msg: string = response?.data?.message ?? message;
          if (msg) {
            createMessage.error(msg);
          }
        }
      }

      return { register, resetFields, handleSubmit, loading };
    },
  });
</script>
